package com.zh.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zh.common.ErrorCode;
import com.zh.domain.Model.ws.SimpleAttacheModel;
import com.zh.domain.Model.ws.SimpleUserModel;
import com.zh.domain.dto.bug.AddBugCommentRequest;
import com.zh.domain.dto.bug.PageBugCommentRequest;
import com.zh.domain.entity.BugComments;
import com.zh.domain.entity.Message;
import com.zh.domain.entity.TaskComments;
import com.zh.domain.vo.bug.BugCommentVo;
import com.zh.domain.vo.bug.BugVo;
import com.zh.domain.vo.task.TaskCommentVo;
import com.zh.domain.vo.task.TaskVo;
import com.zh.domain.vo.user.UserVO;
import com.zh.exception.ThrowUtils;
import com.zh.job.TaskManager;
import com.zh.mapper.BugCommentsMapper;
import com.zh.service.BugCommentsService;
import com.zh.service.BugService;
import com.zh.service.MessageService;
import com.zh.service.UserService;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Administrator
 * @description 针对表【BugComments(缺陷表)】的数据库操作Service
 * @createDate 2025-02-09 16:24:10
 */
@Service
public class BugCommentsServiceImpl extends ServiceImpl<BugCommentsMapper, BugComments>
        implements BugCommentsService {
    @Resource
    private UserService userService;
    @Resource
    private BugService bugService;
    @Resource
    private MessageService messageService;
    @Resource
    private BugCommentsMapper bugCommentsMapper;

    private static final String attacheKey = "A";
    private static final String atUserKey = "M";

    @Override
    @Transactional
    public Boolean addBugComment(AddBugCommentRequest addBugCommentRequest) {
        int loginId = StpUtil.getLoginIdAsInt();
        // 参数校验
        Integer bugId = addBugCommentRequest.getBugId();
        Integer sendId = addBugCommentRequest.getSendId();
        String content = addBugCommentRequest.getContent();
        List<SimpleAttacheModel> attacheList = addBugCommentRequest.getAttacheList();
        List<Integer> atUserList = addBugCommentRequest.getAtUserList();
        ThrowUtils.throwIf(bugId == null, ErrorCode.PARAMS_ERROR, "缺陷id不能为空");
        if (sendId == null) {
            sendId = loginId;
        }
        //2.拼装 附件、@人信息
        Map<String, Object> params = new HashMap<>();

        if (attacheList != null) {
            params.put(attacheKey, JSONUtil.toJsonStr(attacheList));
        }
        if (atUserList != null) {
            List<UserVO> userVOList = userService.listUserVoByIds(atUserList);
            List<SimpleUserModel> simpleUserModelList = userVOList.stream().map(userVO -> {
                SimpleUserModel simpleUserModel = new SimpleUserModel();
                simpleUserModel.setId(userVO.getId());
                simpleUserModel.setName(userVO.getName());
                simpleUserModel.setAvatar(userVO.getAvatar());
                return simpleUserModel;
            }).collect(Collectors.toList());
            params.put(atUserKey, JSONUtil.toJsonStr(simpleUserModelList));
        }
        //3.插入数据库
        BugComments bugComments = BeanUtil.copyProperties(addBugCommentRequest, BugComments.class);
        bugComments.setSendId(sendId);
        bugComments.setParams(params);
        bugComments.setCreateAt(LocalDateTime.now());
        bugComments.setCreateBy(loginId);
        bugComments.setUpdateAt(LocalDateTime.now());
        bugComments.setUpdateBy(loginId);
        bugComments.setStatus(1);
        bugComments.setDeleted(0);
        boolean success = bugCommentsMapper.insert(bugComments) > 0;
        //4.发送消息给被@人
        if (CollectionUtil.isNotEmpty(atUserList)) {
            sendMessageWhenAdd(loginId, bugComments, atUserList);
        }
        return success;
    }

    @Override
    @Transactional
    @Async
    public void sendMessageWhenAdd(Integer sendId, BugComments bugComments, List<Integer> revciverList) {
        Message message = new Message();
        message.setSendId(sendId);
        message.setContent(bugComments.getContent());
        message.setCreateBy(sendId);
        message.setUpdateBy(sendId);
        message.setCreateAt(LocalDateTime.now());
        message.setUpdateAt(LocalDateTime.now());
        message.setNoticeType(1);
        message.setType(4);
        BugVo bugVo = bugService.getDetail(bugComments.getBugId());
        message.setParams(Map.of(
                "bugId", bugComments.getBugId().toString(),
                "payloadType", "bug",
                "title", bugVo.getTitle()
        ));
        messageService.sendMessage(message, revciverList);
    }

    @Override
    public Page<BugCommentVo> pageBugComment(PageBugCommentRequest pageBugCommentRequest) {
        Integer bugId = pageBugCommentRequest.getBugId();
        ThrowUtils.throwIf(null == bugId, ErrorCode.PARAMS_ERROR, "缺陷Id不能为空");
        pageBugCommentRequest.standardizeSize();
        Integer current = pageBugCommentRequest.getCurrent();
        Integer pageSize = pageBugCommentRequest.getPageSize();
        Page<BugComments> page = new Page<>(current, pageSize);
        LambdaQueryWrapper<BugComments> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BugComments::getBugId, bugId)
                .orderByDesc(BugComments::getCreateAt)
                .orderByDesc(BugComments::getId)
        ;
        Page<BugComments> bugCommentsPage = bugCommentsMapper.selectPage(page, queryWrapper);
        List<BugComments> records = bugCommentsPage.getRecords();
        // 获取评论人信息
        List<Integer> userIdList = records
                .stream()
                .map(BugComments::getSendId)
                .collect(Collectors.toList());
        List<UserVO> userVOList = userService.listUserVoByIds(userIdList);
        Map<Integer, UserVO> userVOMap = userVOList.stream().collect(Collectors.toMap(UserVO::getId, userVO -> userVO));
        List<BugCommentVo> resultList = new ArrayList<>();
        records.forEach(bugComments -> {
            BugCommentVo bugCommentVo = BeanUtil.copyProperties(bugComments, BugCommentVo.class);
            UserVO userVO = userVOMap.get(bugComments.getSendId());
            bugCommentVo.setSendUser(userVO);
            resultList.add(bugCommentVo);
        });
        Page<BugCommentVo> pageResult = new Page<>(current, pageSize);
        BeanUtil.copyProperties(bugCommentsPage, pageResult);
        pageResult.setRecords(resultList);
        return pageResult;
    }
}
